package leertaak2;
import java.io.BufferedReader;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileWriter;
import java.io.IOException;
import java.io.InputStreamReader;

/**
 * Class to read a file of a station. If the file does not
 * exist create the file
 * @author marcovellinga
 *
 */
public class Reader {
	
	// Variables
	private File file;
	private BufferedReader in;
	
	/**
	 * Constructor with the filepath
	 * @param path
	 */
	public Reader(String path) {
		
		try {
			FileWriter fileWriter = new FileWriter("/Users/marcovellinga/Desktop/WriterProject/" + path  + ".csv", true);
			fileWriter.close();
			file = new File("/Users/marcovellinga/Desktop/WriterProject/" + path + ".csv");	
		} catch (IOException e1) {
			// TODO Auto-generated catch block
			e1.printStackTrace();
		}
		
	}
	
	/**
	 * Extrapolatie for the temperature. This is to
	 * determine of the value is in the +- 20% range
	 * @param value
	 * @return
	 */
	public String extrapolatieTemp(String value) {
		
		String temp = value;
		double average;
		
		average = Double.parseDouble(extrapolatie(3));
		
		if(Double.parseDouble(temp) < 0.8 * average){
			return Double.toString(Math.round(0.8 * average));
		} else if(Double.parseDouble(temp) > 1.2 * average) {
			return Double.toString(Math.round(1.2 * average));
		} else {
			return temp;
		}
	}
	
	/**
	 * Extrapolatie of data. Check the last 30 values and make
	 * an average of those values.
	 * @param place
	 * @return
	 */
	public String extrapolatie(int place) {
		
		try {
			
			int placeOfDataCount = place;
			in = new BufferedReader (new InputStreamReader (new ReverseLineInputStream(file)));
		
		
		int dividerCounter = 0;
		int currentPlaceCounter = 1;
		double total = 0;
		
		String line = in.readLine();
		    		    
		while (line != null && dividerCounter < 30){
			
			currentPlaceCounter = 1;
		    String[] dataArray = line.split(",");
			for (String item:dataArray) { 
				if(currentPlaceCounter == placeOfDataCount){
					total+= Double.parseDouble(item);
					break;
				}
				currentPlaceCounter++;
			}
			dividerCounter++;
			line = in.readLine();
		}
		
		in.close();
		return Double.toString(Math.round(total/dividerCounter));	
		} catch (FileNotFoundException e) {
		// TODO Auto-generated catch block
		e.printStackTrace();
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		return Double.toString(0.0);
	}
}
